package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExecutTest {
    public static void main(String[] args) { 
        //      ExecutorService executorService = Executors.newCachedThreadPool();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //ExecutorService executorService = Executors.newSingleThreadExecutor();

        CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) { 
            executorService.execute(new TestRunnable(latch)); 
            System.out.println("************* a" + i + " *************"); 
        }
        
        try{
            latch.await();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        //shutdown() 方法在终止前允许执行以前提交的任务
        //第一阶段调用 shutdown 拒绝传入任务，然后调用 shutdownNow（如有必要）取消所有遗留的任务
        //提交的任务运行结束后关闭线程池
        executorService.shutdown(); 
        System.out.println("App exit");
    } 

    static class TestRunnable implements Runnable { 
        CountDownLatch latch;
        public TestRunnable(CountDownLatch latch){
            this.latch = latch;
        }
        public void run() { 
            System.out.println(Thread.currentThread().getName() + "线程被调用了。"); 
            //while (true) { 
                try { 
                    Thread.sleep(1000); 
                    System.out.println(Thread.currentThread().getName()); 
                } catch (InterruptedException e) { 
                    e.printStackTrace(); 
                } finally {
                    latch.countDown();
                }
                
            //} 
        }
    }
}
